﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MINERP.ComControls;
using MINERP.BLL.GoodsDelivery;
using MINERP.COM;
using MINERP.MODEL.GoodsDelivery;


namespace ERPGoodsDelivery
{
    public partial class FrmDeliveryMain :FrmParent
    {
        //参数
        private GoodsDeliveryBLL bll = new GoodsDeliveryBLL();

        private Common.GroupFilter gf = new ERPGoodsDelivery.Common.GroupFilter();  //分组

        //int
        private int MaxDeliveryId;                                          //内存中最大送货单Id

        //viewInfo
        GridHitInfo hitInfo;                                                //鼠标按下处的信息

        //datatable
        public DataTable DeliveryDT;                                        //发货单的整体信息

        public DataTable NoDeliveryDt = null;                               //所有需要发货的账单(分组筛选使用)

        //集合
        private List<int> DeliveryIds = new List<int>();                    //新建的送货单Id集合

        public FrmDeliveryMain()
        {
            InitializeComponent();
        }

        //load方法
        private void FrmDeliveryMain_Load(object sender, EventArgs e)
        {
            try
            {
                //显示所有未发货的账单(包括账单对应的商户明细)
                BindNoDeliveryBill();
                //未打印的发货单
                int noPrint = (int)DeliveryStatus.NoPrint;
                List<BillInfo> NoDeliveryAndPrintBills = bll.GetNoDeliveryBillByStatusOnly(noPrint);
                SetNoPrintBills(NoDeliveryAndPrintBills);
                //数据库中最大的送货单Id
                GetMaxDeliveryId();
                //操作员
                tsUserName.Text = base.userName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //刷新未发货的账单
        private void tsRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                //刷新显示所有未发货的账单(包括账单对应的商户明细)
                BindNoDeliveryBill();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //拖曳分配账单
        private void gvBillInfo_MouseDown(object sender, MouseEventArgs e)
        {
            hitInfo = null;
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            GridHitInfo info = view.CalcHitInfo(e.X, e.Y);
            if (e.Button == MouseButtons.Left && info.InRow && info.HitTest != GridHitTest.RowIndicator)
            {
                hitInfo = info;
            }
        }

        private void gvBillInfo_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && hitInfo != null)
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                try
                {
                    System.Drawing.Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(new Point(hitInfo.HitPoint.X - dragSize.Width / 2, hitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    List<BillInfo> dragBills = new List<BillInfo>();
                    if (!rec.Contains(e.X, e.Y))
                    {
                        //拖曳操作
                        int[] indexes = gvBillInfo.GetSelectedRows();
                        foreach (int index in indexes)
                        {
                            if (view.IsGroupRow(index))
                            {
                                DataRow[] rows = gf.GetGroupRows(view, index, NoDeliveryDt);
                                dragBills.AddRange(bll.ChangeRowsToList(rows));
                            }
                            else
                            {
                                BillInfo bill = gvBillInfo.GetRow(index) as BillInfo;
                                dragBills.Add(bill);
                            }
                        }
                    }
                    if (dragBills.Count == 0)
                        return;
                    DataObject data = new DataObject();
                    data.SetData("dragList", dragBills);
                    DoDragDrop(data, DragDropEffects.All);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        

        //按是否已分配显示背景色
        private void gvBillInfo_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            BillInfo bill = gvBillInfo.GetRow(e.RowHandle) as BillInfo;
            if (bill != null && bill.IsDistributed)
            {
                e.Appearance.BackColor = Color.Pink;
                e.Appearance.BackColor2 = Color.Pink;
            }
        }

        //---------------------对账单堆的操作-------------------

        //新增发货单
        private void tsAddNewDelivery_Click(object sender, EventArgs e)
        {
            try
            {
                //单号
                MaxDeliveryId++;
                MyControl.userDeliveryHeap deliveryHeap = new ERPGoodsDelivery.MyControl.userDeliveryHeap();
                deliveryHeap.DeliveryId = MaxDeliveryId;
                deliveryHeap.SetDeliveryId();
                int h = deliveryHeap.Height;
                int w = deliveryHeap.Width;
                int ph = deliveryHeap.Height;
                deliveryHeap.Height = ph;
                deliveryHeap.Width = Convert.ToInt32(ph * w / h);
                deliveryHeap.BillInfos = new List<BillInfo>();
                deliveryHeap.Dock = DockStyle.Left;
                //事件
                deliveryHeap.userDeliveryHeapDragDrop += new DragEventHandler(userDeliveryHeapDragDrop);
                deliveryHeap.userDeliveryHeapDragEnter += new DragEventHandler(userDeliveryHeapDragEnter);
                deliveryHeap.userDeliveryHeapDragEnter += new DragEventHandler(userDeliveryHeapDragOver);
                deliveryHeap.userClick += new EventHandler(deliveryHeap_userClick);
                pDeliveryHeap.Controls.Add(deliveryHeap);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //删除发货单
        private void tsDeleteDelivery_Click(object sender, EventArgs e)
        {
            try
            {
                if (pDeliveryHeap.Controls == null || pDeliveryHeap.Controls.Count == 0)
                {
                    MessageBox.Show("当前没有货物分堆!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                bool isHaveHeap = false;
                foreach (Control c in pDeliveryHeap.Controls)
                {
                    if (c.BackColor == Color.Pink)
                    {
                        isHaveHeap = true;
                        if (DialogResult.Yes == MessageBox.Show("确定要删除货物分堆吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                        {
                            //取消堆内的账单
                            MyControl.userDeliveryHeap delHeap = c as MyControl.userDeliveryHeap;
                            if (delHeap.BillInfos.Count > 0)
                            {
                                bll.DelBillFromDeliveryInfo(delHeap.BillInfos);
                                //刷新
                                BindNoDeliveryBill();
                                gcBillInfoHeap.DataSource = null;
                                gcBillInfoHeap.RefreshDataSource();
                            }
                            pDeliveryHeap.Controls.Remove(c);
                            return;
                        }
                    }
                }
                if (isHaveHeap == false)
                {
                    MessageBox.Show("没有货物分堆被选中!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //打印发货单
        private void tsPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (pDeliveryHeap.Controls == null || pDeliveryHeap.Controls.Count == 0)
                {
                    MessageBox.Show("没有发货单格子被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                bool isHaveHeapSelected = false;
                MyControl.userDeliveryHeap selectedHeap = null;
                foreach (Control c in pDeliveryHeap.Controls)
                {
                    MyControl.userDeliveryHeap heap = c as MyControl.userDeliveryHeap;
                    if (heap.BackColor == Color.Pink)
                    {
                        isHaveHeapSelected = true;
                        selectedHeap = heap;
                        break;
                    }
                }
                if (isHaveHeapSelected == false)
                {
                    MessageBox.Show("没有发货单格子被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                Cursor = Cursors.WaitCursor;
                //设置发货单整体信息
                Delivery.FrmSelectUser su = new ERPGoodsDelivery.Delivery.FrmSelectUser();
                su.main = this;
                su.DeliverId = selectedHeap.DeliveryId;
                if (DialogResult.OK != su.ShowDialog())
                {
                    Cursor = Cursors.Default;
                    return;
                }
                //修改发货单状态
                int printedStatus = (int)DeliveryStatus.Printed;
                bll.ChangeDeliveryStatus(printedStatus, su.DeliverId,su.UserId);

                //打印
                DataSet ds = bll.GetPrintData(selectedHeap.BillInfos, DeliveryDT);      //DeliveryDT是从选择发货员工界面获得
                FastReport.Report report = new FastReport.Report();
                report.Load(Application.StartupPath + "\\DeliveryInfo.frx");
                report.Show();
                //移除当前发货单
                RemoveHeap();
                gcBillInfoHeap.DataSource = null;
                gcBillInfoHeap.RefreshDataSource();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //取消账单
        private void tsCancelBill_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvBillInfoHeap.SelectedRowsCount == 0)
                {
                    MessageBox.Show("没有账单被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DialogResult.Yes == (MessageBox.Show("确定要删除选定的账单吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)))
                {
                    int[] indexes = gvBillInfoHeap.GetSelectedRows();
                    List<BillInfo> DelBills = new List<BillInfo>();
                    foreach (int index in indexes)
                    {
                        if (index < 0)
                            continue;
                        BillInfo bill = gvBillInfoHeap.GetRow(index) as BillInfo;
                        DelBills.Add(bill);
                    }
                    if (DelBills.Count == 0)
                        return;
                    bll.DelBillFromDeliveryInfo(DelBills);
                    //刷新
                    BindNoDeliveryBill();
                    foreach (MyControl.userDeliveryHeap heap in pDeliveryHeap.Controls)
                    {
                        if (heap.BackColor == Color.Pink)
                        {
                            int noPrintStatus = (int)DeliveryStatus.NoPrint;
                            heap.BillInfos = bll.GetNoDeliveryBillByStatus(heap.DeliveryId, noPrintStatus);
                            heap.BillNum = heap.BillInfos.Count;
                            heap.SetBillNum();
                            SetHeapBills(heap.BillInfos);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //调用发货反馈
        private void tsBack_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                Delivery.FrmDeliverBack back = ERPGoodsDelivery.Delivery.FrmDeliverBack.GetInstance;
                back.Show();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //查询发货信息
        private void tsFind_Click(object sender, EventArgs e)
        {
            try
            {
                Delivery.FrmDeliverFind form = Delivery.FrmDeliverFind.GetInstance;
                form.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //设置基础信息
        private void tsSetBaseInfo_Click(object sender, EventArgs e)
        {
            try
            {
                Delivery.FrmBaseInfo baseInfo = Delivery.FrmBaseInfo.GetInstance;
                baseInfo.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //不需要发货的账单
        private void tsRemoveNoNeedDeliverBill_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvBillInfo.SelectedRowsCount == 0)
                {
                    MessageBox.Show("没有账单被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DialogResult.Yes == (MessageBox.Show("确定选中的账单不需要发货吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)))
                {
                    List<int> billIds = new List<int>();
                    int[] indexes = gvBillInfo.GetSelectedRows();
                    foreach (int index in indexes)
                    {
                        BillInfo bill = gvBillInfo.GetRow(index) as BillInfo;
                        billIds.Add(bill.BillId);
                    }
                    bll.DelNeedDeliver(billIds);
                    //刷新
                    BindNoDeliveryBill();
                    gcBillInfoHeap.DataSource = null;
                    gcBillInfoHeap.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改界面
        private void tsModifyDeliver_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                Delivery.FrmModify m = Delivery.FrmModify.GetInstance;
                m.Show();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void tsReturn_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                Return.FrmReturnBase frm = Return.FrmReturnBase.GetInstance;
                frm.Show();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //----------------------------------------------------------------------
        //--------------公共方法------------------------------------------------
        #region 获取所有未发货的账单
        /// <summary>
        /// 获取所有未发货的账单
        /// </summary>
        private void BindNoDeliveryBill()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                List<BillInfo> billInfos = bll.GetNoDeliveryBill(out NoDeliveryDt);
                gcBillInfo.DataSource = billInfos;
                gcBillInfo.RefreshDataSource();
                lblBillNum.Text = billInfos.Count.ToString();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                throw ex;
            }
        }
        #endregion

        #region 设置还未打印的发货单堆
        /// <summary>
        /// 设置还未打印的发货单堆
        /// </summary>
        /// <param name="noPrintBills"></param>
        private void SetNoPrintBills(List<BillInfo> noPrintBills)
        {
            try
            {
                var deliverHeaps = noPrintBills.GroupBy(p => p.DeliverId);
                foreach (var heap in deliverHeaps)
                {
                    //创建发货单格子
                    MyControl.userDeliveryHeap dh = new ERPGoodsDelivery.MyControl.userDeliveryHeap();
                    dh.DeliveryId = heap.First().DeliverId;
                    dh.BillNum = heap.Count();
                    int h = dh.Height;
                    int w = dh.Width;
                    int ph = dh.Height;
                    dh.Height = ph;
                    dh.Width = Convert.ToInt32(ph * w / h);
                    dh.Dock = DockStyle.Left;
                    //事件
                    dh.userDeliveryHeapDragDrop += new DragEventHandler(userDeliveryHeapDragDrop);
                    dh.userDeliveryHeapDragEnter += new DragEventHandler(userDeliveryHeapDragEnter);
                    dh.userDeliveryHeapDragEnter += new DragEventHandler(userDeliveryHeapDragOver);
                    dh.userClick += new EventHandler(deliveryHeap_userClick);
                    pDeliveryHeap.Controls.Add(dh);
                    //发货单格子的账单明细
                    dh.BillInfos = heap.ToList();
                    dh.SetBillNum();
                    dh.SetDeliveryId();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        public void userDeliveryHeapDragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("dragList"))
            {
                e.Effect = DragDropEffects.All;
                MyControl.userDeliveryHeap heap = sender as MyControl.userDeliveryHeap;
                heap.BorderStyle = BorderStyle.Fixed3D;
            }
        }

        public void userDeliveryHeapDragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("dragList"))
            {
                MyControl.userDeliveryHeap heap = sender as MyControl.userDeliveryHeap;
            }
        }

        public void userDeliveryHeapDragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("dragList"))
            {
                if (DialogResult.Yes == (MessageBox.Show("确定将选中的账单分配给该送货单吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)))
                {
                    MyControl.userDeliveryHeap heap = sender as MyControl.userDeliveryHeap;
                    List<BillInfo> bills = e.Data.GetData("dragList") as List<BillInfo>;
                    //账单插入数据库
                    bll.InsertDeliveryNoPrint(bills, heap.DeliveryId);
                    //刷新
                    BindNoDeliveryBill();
                    int noPrintStatus = (int)DeliveryStatus.NoPrint;
                    heap.BillInfos = bll.GetNoDeliveryBillByStatus(heap.DeliveryId, noPrintStatus);
                    heap.BillNum = heap.BillInfos.Count;
                    heap.SetBillNum();
                    deliveryHeap_userClick(sender, e);
                }
            }
        }


        void deliveryHeap_userClick(object sender, EventArgs e)
        {
            MyControl.userDeliveryHeap dh = sender as MyControl.userDeliveryHeap;
            if (dh.BackColor == Color.Pink)
            {
                SetHeapBills(dh.BillInfos);
                return;
            }
            else
            {
                //设置堆内数据源
                SetHeapBills(dh.BillInfos);

                dh.BackColor = Color.Pink;
                foreach (Control c in pDeliveryHeap.Controls)
                {
                    MyControl.userDeliveryHeap dhc = c as MyControl.userDeliveryHeap;
                    if (dhc != dh && dhc.BackColor == Color.Pink)
                    {
                        dhc.BackColor = Color.Empty;
                        break;
                    }
                }
            }
        }

        #region 绑定堆内数据源
        /// <summary>
        /// 绑定堆内数据源
        /// </summary>
        /// <param name="bills"></param>
        private void SetHeapBills(List<BillInfo> bills)
        {
            gcBillInfoHeap.DataSource = bills;
            gcBillInfoHeap.RefreshDataSource();
        }
        #endregion

        #region 设置数据库中最大的送货单Id
        /// <summary>
        /// 设置数据库中最大的送货单Id
        /// </summary>
        public void GetMaxDeliveryId()
        {
            try
            {
                MaxDeliveryId = bll.GetMaxDeliveryId();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 移除当前已打印的发货单
        /// <summary>
        /// 移除当前已打印的发货单
        /// </summary>
        private void RemoveHeap()
        {
            try
            {
                foreach (Control c in pDeliveryHeap.Controls)
                {
                    if (c.BackColor == Color.Pink)
                    {
                        pDeliveryHeap.Controls.Remove(c);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private void toolStripButtonPrintShipping_Click(object sender, EventArgs e)
        {
            FrmShippingFee frm = new FrmShippingFee();
            frm.UserID = base.userId;
            frm.ShowDialog();
        }

    }
}
